<?php
/**
 * @Author: Zhaojun(13040@qq.com)
 * @Date:   2018-07-11 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-03-17 16:29:21
 */

namespace app\actstar\controller;

class SignupSubmit extends ActstarBase {

	function initialize() {
		parent::initialize();
		$this->activeDao = model('actstar_manage/Active');
		$this->activeMeetingDao = model('actstar_manage/ActiveMeeting');
		$this->signupDao = model('actstar_manage/Signup');
		$this->userDao = model('actstar_manage/User');
	}

	//确认并生成报名信息
	public function doSubmit() {
		$this->checkIsLoginAjax(); //提示用户登陆状态

		$initKid = input('post.initKid', '', '', 'intval');
		$buyNum = input('post.buyNum', '', '', 'intval');
		//获取活动信息
		$activeInfo = $this->activeDao->getInfo($initKid);
		//验证数据
		if (!$this->activeDao->verifyData($activeInfo, $this->ts)) {
			$this->error($this->activeDao->getError());
		}
		//验证高级数据
		if (!$this->activeDao->verifySeniorData($activeInfo, $this->ts)) {
			$this->error($this->activeDao->getError());
		}
		//留言字段相关
		if ($activeInfo['is_signup_open']) {
			$leavemessInput = input('post.leavemessInput/a', '', '', 'pwEscape');
			if ($activeInfo['leavemess_fields_arr']) {
				foreach ($activeInfo['leavemess_fields_arr'] as $key => $value) {
					if ($value['is_require']) {
						if (!$leavemessInput[$value['flag']]) {
							$this->error('请输入'.$value['name']);
						}
					}
					if ($value['issys'] == 1) {
						if ($value['flag'] == 'personnum') {
							if (!$leavemessInput[$value['flag']]) {
								$this->error('请输入报名人数');
							}
							if ($activeInfo['limit_person_num'] && $leavemessInput[$value['flag']] > $activeInfo['limit_person_num']) {
								$this->error('一次最多报名人数'.$activeInfo['limit_person_num']);
							}
						}
						if ($value['flag'] == 'personsex') {
							$frontsex_config = config('frontsex_config');
							$leavemessInput['personsex_cn'] = $frontsex_config[$leavemessInput['personsex']];
						}
						if ($value['flag'] == 'mobile' && $value['is_require']) {
							if (!preg_match("/^1[0-9]{10}$/", $leavemessInput['mobile'])) {
								procUnLock('signup_submit', $this->moonuid); //物理锁
								$this->error('请输入正确的手机号码');
							}
						}
						//限制手机号唯一
						if ($activeInfo['is_mobile_unique'] && $value['flag'] == 'mobile') {
							$checkRepeat = $this->signupDao->checkMobileRepeat($initKid, $leavemessInput['mobile']);
							if ($checkRepeat >= 1) {
								procUnLock('signup_submit', $this->moonuid); //物理锁
								if ($initKid == 11) {
									$this->error('您已报名成功，请勿重复报名，点击直播间入口即可观看直播');
								} else {
									$this->error('该手机号码已经报名，请勿重复报名，重新打开该页面可以看到报名信息');
								}
							}
						}
						if ($activeInfo['is_mobileplace_limit'] && $value['flag'] == 'mobile') {
							//获取手机归属地
							$checkMobile = substr($mobile, 0, 7); //再检测一遍
							$checkInfo = model('PwHackLocalmobile')->findInfo(['submobile'=>$checkMobile]);
							if (!$checkInfo) {
								$this->error('活动仅限苏州地区手机号码参加，如有问题，请联系客服微信：18020206060');
							} else {
								$mobile_source = iconv('gbk', 'utf-8', $checkInfo['city']);
							}
							$leavemessInput['mobile_source'] = $mobile_source;
							$checkInfo = $this->userDao->findInfo(['kid'=>$kid, 'mobile'=>$mobile]);
							if ($checkInfo) {
								$this->error('该手机已经绑定用户，请勿重复绑定');
							}
						}
					} else if ($value['issys'] == 0) {
						if ($value['type'] == 'checkbox') {
							if ($value['is_require'] && !$leavemessInput[$value['flag']]) {
								$this->error('请选择'.$value['name']);
							}
							if ($leavemessInput[$value['flag']]) {
								$newValue = implode(",", $leavemessInput[$value['flag']]);
								$leavemessInput[$value['flag']] = $newValue;
							}
						}
					}
				}
			}
		}
		//print_r($leavemessInput);exit;

		//=====定位限制地区
		$longitude = $this->moondb['longitude'];
		$latitude = $this->moondb['latitude'];
		$accuracy = $this->moondb['accuracy'];
		$location_address = $location_city = $location_district = $sematic_description = '';
		if ($activeInfo['is_location_open']) {
			if ($longitude == '0.0000000') {
				$this->error('请先开启定位功能再进行操作~');
			}
			//根据坐标获取地址(百度)
			$latlng = $latitude.','.$longitude;
			db('Aaaa')->insert(['space'=>'actstar', 'module'=>'location', 'flag'=>'latlng', 'content'=>$latlng]);
			$url = "http://api.map.baidu.com/geocoder/v2/?location=".$latlng."&output=json&pois=1&ak=".config('baiduAK');
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8")); //Header部分的Content-type要设置
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
			curl_setopt($ch, CURLOPT_REFERER, 'http://'.$_SERVER['HTTP_HOST']);
			$output = curl_exec($ch);
			curl_close($ch);
			$resultJson = json_decode($output, true);
			//print_r($resultJson);exit;
			db('Aaaa')->insert(['space'=>'actstar', 'module'=>'location', 'flag'=>'resultJson', 'content'=>pw_var_export($resultJson)]);
			if ($resultJson['status']) {
				//$this->error('code:'.$resultJson['status'].';'.$resultJson['msg']);
			} else {
				$result = $resultJson['result'];
				$location_address = $result['formatted_address'];
				$addressComponent = $result['addressComponent'];
				$location_city = $addressComponent['city'];
				$location_district = $addressComponent['district'];
				$sematic_description = $result['sematic_description'];
			}
			if ($activeInfo['is_location_limit']) {
				$limitCity = explode(",", $activeInfo['location_cityname']);
				$isAllow = 0;
				foreach ($limitCity as $key => $value) {
					if (strpos($location_city, $value)!==false) {
						$isAllow = 1;
						break;
					}
					if (strpos($location_district, $value)!==false) {
						$isAllow = 1;
						break;
					}
				}
				if (!$isAllow) {
					$resultMsg = '您所在的区域为'.$location_city.'，不符合本次活动规定。('.$activeInfo['location_cityname'].')';
					//日志入库
					$logDao = model('actstar_manage/Log');
					$data = array(
						'uid'				=> $this->moonuid,
						'pwuid'				=> $this->moonpwuid,
						'openid'			=> $this->moondb['openid'],
						'unionid'			=> $this->moondb['unionid'],
						'username'			=> $this->moonname,
						'create_time'   	=> $this->ts,
						'content'			=> $resultMsg,
						'extra1'			=> $location_address,
						'extra2'			=> $location_city,
						'extra3'			=> $location_district,
						'extra4'			=> pw_var_export($resultJson),
					);
					$logDao->baseAddData($data);
					$this->error($resultMsg);
				}
			}
		}
		
		if (procLock('signup_submit', $this->moondb['uid'])) { //物理锁
			$this->signupDao->startTrans(); //开启事务
			//获取用户总次数
			$signupTotalNum = $this->signupDao->getUserCountByKidAndUid($kid, $this->moonuid);
			//=====限制用户参与总次数
			if ($activeInfo['limit_total_num']) {
				$tmpLimitNum = $activeInfo['limit_total_num'];
				if ($activeInfo['limit_total_share_num']) {
					if ($this->moondb['is_share']) {
						$tmpLimitNum += $activeInfo['limit_total_share_num'];
					}
				}
				if ($signupTotalNum >= $tmpLimitNum) {
					procUnLock('signup_submit', $this->moonuid); //物理锁
					if ($activeInfo['limit_total_tip']) { //自定义提示
						$tipmsg = str_replace(array("{limit_total_num}"), array($activeInfo['limit_total_num']), $activeInfo['limit_total_tip']);
						$this->error($tipmsg, '', $resultData);
					} else {
						$this->error('您的抽奖次数已满，每人最多允许抽'.$activeInfo['limit_total_num'].'次', '', $resultData);
					}
				}
			}
			//=====限制用户每日参与次数
			if ($activeInfo['limit_day_num']) {
				$recordTodayNum = $this->signupDao->getUserTdCountByKidAndUid($kid, $this->moonuid, $this->tdtime);
				$tmpLimitNum = $activeInfo['limit_day_num'];
				if ($activeInfo['limit_day_share_num']) {
					//获取用户分享数据
					$checkShareInfo = $this->shareDao->getUserTdCountByKidAndUid($kid, $this->moonuid, $this->tdtime);
					if ($checkShareInfo) {
						$tmpLimitNum += $activeInfo['limit_day_share_num'];
					}
				}
				if ($recordTodayNum >= $tmpLimitNum) {
					procUnLock('signup_submit', $this->moonuid); //物理锁
					if ($activeInfo['limit_day_tip']) { //自定义提示
						$tipmsg = str_replace(array("{record_today_num}", "{limit_day_num}", "{limit_day_share_num}"), array($recordTodayNum, $activeInfo['limit_day_num'], $activeInfo['limit_day_share_num']), $activeInfo['limit_day_tip']);
						$this->error($tipmsg, '', $resultData);
					} else {
						if ($activeInfo['limit_day_share_num']) {
							$this->error('您今日已经参与'.$recordTodayNum.'次，每日只允许参与'.$activeInfo['limit_day_num'].'次（额外增加分享'.$activeInfo['limit_day_share_num'].'次）', '', ['mode'=>'alert']);
						} else {
							$this->error('您今日已经参与'.$recordTodayNum.'次，每日只允许参与'.$activeInfo['limit_day_num'].'次', '', $resultData);
						}
					}
				}
			}
			//开启场次的情况
			if ($activeInfo['is_meeting_open']) {
				$initMeid = input('param.initMeid', '', '', 'intval');
				if ($initMeid) {
					$meetingInfo = $this->activeMeetingDao->getInfo($initMeid);
					//验证场次库存
					if ($meetingInfo['stock_num']) {
						$meetingRecordRecordNum = $this->signupDao->countSearch(['kid'=>$kid, 'meid'=>$initMeid]);
						if ($meetingRecordRecordNum > $meetingInfo['stock_num']) {
							$this->error('该场次名额已达上限，无法报名');
						}
					}
					//验证场次人数
					if ($meetingInfo['person_num']) {
						$meetingRecordPersonNum = $this->signupDao->baseSumSearch(['kid'=>$kid, 'meid'=>$initMeid], 'personnum');
						if ($meetingRecordRecordNum > $meetingInfo['stock_num']) {
							$this->error('该场次报名人数已达上限，无法报名');
						}
					}
				} else {
					$this->error('请选择场次');
				}
			} else {
				$initMeid = 0;
			}
			//获取ip地址
			$request = request();
			$ipaddr = $request->ip();
			$IpLocation = new \org\util\IpLocation();
			$ipfrom = $IpLocation->ip2addr($ipaddr);
			
			if ($activeInfo['real_price'] == '0.00') {
				$signup_status = 2; //报名状态
			} else {
				$signup_status = 1; //报名状态
			}
			
			//=====生成报名信息
			$orderNo = $this->_build_order_no($this->moonuid);
			if ($activeInfo['real_price'] != '0.00') {
				if ($activeInfo['is_personnum_pprice']) { //计算报名人数支付价格
					$totalFee = $activeInfo['real_price']*$leavemessInput['personnum'];
				} else {
					$totalFee = $activeInfo['real_price'];
				}
			} else {
				$totalFee = 0;
			}
			$data = array(
				'kid'					=> $initKid,
				'meid'					=> $initMeid,
				'uid'					=> $this->moonuid,
				'openid'      			=> $this->moondb['openid'],
				'unionid'      			=> $this->moondb['unionid'],
				'username'      		=> $this->moonname,
				'gender'				=> $this->moondb['gender'],
				'city'					=> $this->moondb['city'],
				'province'				=> $this->moondb['province'],
				'country'				=> $this->moondb['country'],
				'del_status'			=> 1, //删除状态
				'signup_status'			=> $signup_status, //报名状态
				'pay_status'			=> 1, //交易状态
				'writeoff_status'		=> 1, //核销状态
				'create_time'   		=> $this->ts,
				'order_no'				=> $orderNo,
				'total_fee'				=> $totalFee, //应付金额
				'ipaddr'				=> $ipaddr,
				'ipfrom'				=> $ipfrom,
				'longitude'				=> $longitude,
				'latitude'				=> $latitude,
				'accuracy'				=> $accuracy,
				'location_address'		=> $location_address,
				'location_city'			=> $location_city,
				'location_district'		=> $location_district,
				'sematic_description'	=> $sematic_description,
			);
			$data += $leavemessInput;
			db('Aaaa')->insert(['space'=>'actstar', 'module'=>'signupSubmit', 'flag'=>'data', 'content'=>pw_var_export($data)]);
			$signupId = $this->signupDao->baseAddData($data);
			//echo $this->signupDao->getLastSql();exit;
			if ($signupId === false) {
				procUnLock('signup_submit', $this->moonuid); //物理锁
				$this->error('报名记录生成非法'.showDbError($this->signupDao));
			}

			//=====更新用户信息
			if ($leavemessInput) {
				unset($leavemessInput['personnum']);
				db('Aaaa')->insert(['space'=>'actstar', 'module'=>'signupSubmit', 'flag'=>'leavemessInput', 'content'=>pw_var_export($leavemessInput)]);
				//print_r($leavemessInput);exit;
				$result = $this->userDao->baseUpdateData($this->moonuid, $leavemessInput);
			}

			//=====更新活动库存
			$this->activeDao->where(['id'=>$initKid])->setDec('stock_num', $buyNum);
			$this->activeDao->where(['id'=>$initKid])->setInc('signup_num', 1);
			if ($leavemessInput['personnum']) {
				$this->activeDao->where(['id'=>$initKid])->setInc('person_num', $leavemessInput['personnum']);
			} else {
				$this->activeDao->where(['id'=>$initKid])->setInc('person_num', 1);
			}
			$this->signupDao->commit(); //事务提交
			procUnLock('signup_submit', $this->moonuid); //物理锁
			if ($activeInfo['eject_link']) {
				$this->success('报名成功，请观看直播', $activeInfo['eject_link']);
			} else {
				$this->success('报名成功', url('actstar/mySignup/detail', ['signupId'=>$signupId]));
			}
		} else {
			procUnLock('signup_submit', $this->moonuid); //物理锁
			$this->error('请重新操作');
		}
	}

	private function _build_order_no($uid) {
		return 'FS'.date('ymdhis').rand(10, 99).str_pad($uid, 6, "0", STR_PAD_LEFT);
	}
	
}